package com.tz.test.config;

import com.tz.test.listener.BsDataSyncListener;
import lombok.Data;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhangky
 * @since 2020/5/6
 */
@Configuration
@Data
public class RabbitMQConfig {

    @Value("${file.rabbitmq.port}")
    private Integer port;
    @Value("${file.rabbitmq.host}")
    private String host;
    @Value("${file.rabbitmq.username}")
    private String username;
    @Value("${file.rabbitmq.password}")
    private String password;
    @Value("${file.rabbitmq.connectionTimeout}")
    private long connectionTimeout;

    private CachingConnectionFactory.CacheMode cacheMode;
    private int channelCacheSize;
    private long channelCheckoutTimeout;

    @Bean("cachingConnectionFactory")
    public CachingConnectionFactory connectionFactory() {
        CachingConnectionFactory cachingConnectionFactory=new CachingConnectionFactory();
        cachingConnectionFactory.setHost(host);
        cachingConnectionFactory.setPort(port);
        cachingConnectionFactory.setUsername(username);
        cachingConnectionFactory.setPassword(password);
        cachingConnectionFactory.setVirtualHost("/");
        cachingConnectionFactory.setPublisherConfirms(true);
        if(cacheMode !=null){
            cachingConnectionFactory.setCacheMode(cacheMode);
        }
        if(channelCacheSize>0){
            cachingConnectionFactory.setChannelCacheSize(channelCacheSize);
        }
        if(channelCheckoutTimeout>0){
            cachingConnectionFactory.setChannelCheckoutTimeout(channelCheckoutTimeout);
        }
        return cachingConnectionFactory;
    }

    /**
     * 创建监听器，监听队列
     * @param bsDataSyncListener 监听方法
     * @return 监听器
     */
    @Bean
    public SimpleMessageListenerContainer messageListenerContainer(BsDataSyncListener bsDataSyncListener, @Qualifier("cachingConnectionFactory") CachingConnectionFactory cachingConnectionFactory){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cachingConnectionFactory);
        // 监听队列的名称
        container.setQueueNames("wts.queue.receChanged.bs");
        container.setExposeListenerChannel(true);
        // 设置每个消费者获取的最大消息数量
        container.setPrefetchCount(100);
        // 消费者的个数
        container.setConcurrentConsumers(1);
        // 设置确认模式为手工确认
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setMessageListener(bsDataSyncListener);
        return container;
    }

}
